<?php

namespace app\controllers;

use app\controllers\admin\uni\order\OrderController;
use app\controllers\pay\PayRefund;
use app\controllers\wx\services\Template;
use app\models\ExpressCallback as Model;
use app\models\order\Order;
use app\models\SetExpressApi;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\UserBalance;
use app\util\Debug;
use app\util\Request;

/**
 * Class SiteController
 * @package app\controllers
 */
class ExpressController extends Controller
{

    public $enableCsrfValidation = false;

    // 快递推送
    public function actionIndex()
    {
        $data = $this->post();

        if ($data) {
            // $data = json_decode($data, true);

            // Debug::debug('express-data', json_encode($data));


            $model = Model::findOne(['waybill' => $data['waybill'], 'shopbill' => $data['shopbill']]);
            if (!$model) {
                $model = new Model();
            }

            // 订单状态
            // Template::expressStatus($model);


            $data = ['ExpressCallback' => $data];
            if ($model->load($data) && $model->save()) {
                // return '{"code":1,"message":"推送成功"}';

                // 订单状态
                // Template::expressStatus($model);

                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    $order = Order::findOne([
                        'waybill' => $model->waybill,
                        'shopbill' => $model->shopbill,
                    ]);
                    if ($order) {
                        $freight = $model->totalFreight * (1 + SetExpressApi::getLastOne()->ratio / 100);
                        if ($freight > $order->total_pay) {
                            $order->add_freight = $freight - $order->total_pay;
                            $order->save();
                        }

                        // 小程序发货
                        if ($model->typeCode != 99) {
                            // 关掉了, 他手动操作
                            // OrderController::miniExpress($order->id);
                        }

                        // typeCode	int	状态码（1.待揽收 2.运输中 3.已签收 4.拒收退回 99.已取消）
                        if ($model->typeCode == 99) {
                            // $order->status = Order::$statusMapping['REFUND'];
                            // $order->save();

                            // Debug::debug('a', 'fff');

                            // 这里还要退款
                            // 这里退款成功, 改变状态
                            PayRefund::refund($order->id);
                        }

                        if ($model->typeCode != 2 && $model->typeCode != 99) {
                            Template::expressStatus($model);
                        }

                        // 处理佣金, 3 已签收
                        if ($model->typeCode == 3) {
                            // 不需要补运费
                            // 注意这里,
                            // add_freight => 0.0019999999999988916
                            // 可能是decimal 默认值
                            if ($order->add_freight <= 0.01 || ($order->add_freight > 0 && $order->add_freight_ok == 1)) {
                                $commissions = UserCommission::find()
                                    ->where(['order_id' => $order->id])
                                    ->andWhere(['status' => 0])
                                    ->all();
                                if (empty($commissions)) {
                                    // Debug::debug('express-empty', '没有佣金');
                                }

                                foreach ($commissions as $c) {
                                    $c->status = 1;
                                    $c->save();

                                    $account = UserAccount::findOne(['user_id' => $c->user_id]);
                                    if ($account) {
                                        if ($account->await_balance >= $c->balance) {

                                            UserBalance::addLog($c->user_id,
                                                $account->balance, $c->balance, $account->balance + $c->balance, $c->award_name, $c->order_id);

                                            $account->await_balance -= $c->balance;
                                            $account->done_balance += $c->balance;
                                            $account->balance += $c->balance;
                                            $account->save();

                                            // 消息
                                            Template::commission($order, $c->balance, $c->user_id);
                                        } else {
                                            Debug::debug('express-await', '待返不足');
                                        }
                                    } else {
                                        Debug::debug('express-account', '帐户不存在');
                                    }
                                }

                                // 订单完成
                                $order->status = Order::$statusMapping['FINISH'];
                                $order->save();

                                // 推送完成, 其实这个状态也没有什么用
                                $model->status = 1;
                                $model->save();


                            } else {
                                Debug::debug('express-order-info', json_encode($order->toArray()));
                                Debug::debug('express-order', $order->id .
                                    ' => ' . ($order->add_freight <= 0 || ($order->add_freight > 0 && $order->add_freight_ok == 1) ? 'true' : 'false'));
                            }
                        }
                    }

                    $transaction->commit();
                    return $this->json(null, '推送成功', 1);

                } catch (\Exception $e) {
                    $transaction->rollBack();
                    Debug::debug('express-fail', $e->getMessage());
                }


                // return $this->json(null, '推送成功', 1);
            } else {
                Debug::debug('express-error', json_encode($data));
            }
        }

        return '没有收到数据';
    }


}
